<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
set_time_limit(60);
// 需要先前往官网注册账号，生成自己的apiKey输入在下面就行了 有几十款大模型都免费！
// 官网:https://cloud.siliconflow.cn/i/GV4z9jcA
$apiKey = 'API 密钥'; // 替换为你的 API 密钥
$input = json_decode(file_get_contents('php://input'), true);
$userMessage = !empty($input['message'] )?$input['message'] : '';
if (empty($userMessage)) {
    echo "data: [ERROR] No message provided\n\n";
    flush();
    exit;
}
$data = [
    'model' => 'deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B',
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => $userMessage],
    ],
    'stream' => true,
];
$ch = curl_init('https://api.siliconflow.cn/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) {
    echo $chunk;
    ob_flush();
    flush();
    return strlen($chunk);
});
$response = curl_exec($ch);
if (curl_errno($ch)) {
    echo "data: [ERROR] " . curl_error($ch) . "\n\n";
    ob_flush();
    flush();
}
curl_close($ch);